import { message, Modal } from 'ant-design-vue'
import { computed, nextTick, onUnmounted, reactive, ref, watch } from 'vue'
import componentsConfig from '../config/components'
import type { EditorState, EditorHeaderState, ComponentArrayConfig, ConfigComponent, ComponentsConfig } from '../types'
import Driver from 'driver.js'
import 'driver.js/dist/driver.min.css'
// import Sortable from 'sortablejs'
import { getEditorStateForLocal, saveEditorStateForLocal } from '../db'

import { isMacOS } from '@/components/cms/utils'
import { debugRun } from '@cms/utils'
import config from '../config'
let saveIng = false
// 全局状态管理
export const editorState = reactive<EditorState>(await getEditorStateForLocal())

watch(
  () => editorState.menu.selectedKeys,
  (val) => {
    editorState.menu.selectedKey = val?.length ? val[0] : ''
  },
  { immediate: true }
)

watch(editorState, (v) => nextTick(() => saveEditorStateForLocal(v)), {
  deep: true
})
// 设置 header state.value
export const setHeaderProps = <K extends keyof EditorHeaderState>(key: K, value: EditorHeaderState[K]) => {
  editorState.header[key] = value
}

// 当前面板配置
export const panelConfig = computed(() => {
  return function (cType: 'adv' | 'comp'): ComponentArrayConfig {
    const res: ComponentArrayConfig = {
      default: '',
      components: []
    }
    if (!editorState.menu.selectedKeys?.length) return res
    if (!cType) return res

    const components: ConfigComponent[] = []
    const key = editorState.menu.selectedKey
    if (Object.keys(componentsConfig).includes(key)) {
      const cfg = componentsConfig[key] as ComponentsConfig
      // 设置默认选中
      res.default = cfg.default

      res.key = cfg.key

      const compMaps = cfg.components
      // .map 组装结构
      // .sort 排序
      const comps: ConfigComponent[] = Object.keys(compMaps)
        .map((k) => ({ key: k, ...compMaps[k] } as unknown as ConfigComponent))
        .sort((a, b) => a.sort - b.sort)
      components.push(...comps.filter((item) => item.type === cType))
    }
    res.components = components

    return res
  }
})
/** 当前选中的  组件 */
export const currentCheckedComponent = computed<string | undefined>(
  () => editorState.componentPanel.checked ?? panelConfig.value('comp').default
)

/** 禁用Contextmenu */
const handleDisabledContextmenu = (e: MouseEvent) => {
  e.preventDefault()
  e.stopPropagation()
  return false
}
/** 禁用Contextmenu */
export const disableContextmenu = (el: HTMLElement | undefined) => {
  if (el && !editorState.debug) {
    el.addEventListener('contextmenu', handleDisabledContextmenu, false)
    onUnmounted(() => {
      el.removeEventListener('contextmenu', handleDisabledContextmenu, false)
    })
  }
}

/** 绑定快捷键 */
const handleShortcutKey = (event: KeyboardEvent) => {
  if (event.code === 'KeyF') {
    editorState.zoom = 1
  }
  if (isMacOS() ? event.metaKey : event.ctrlKey && event.code === 'Minus') {
    event.preventDefault()
    event.stopPropagation()
    const value = editorState.zoom - 0.05
    editorState.zoom = value > 0.05 ? value : 0.05
  }

  if (isMacOS() ? event.metaKey : event.ctrlKey && event.code === 'Equal') {
    event.preventDefault()
    event.stopPropagation()
    const value = editorState.zoom + 0.05
    editorState.zoom = value < 4 ? value : 4
  }
}

/** 监听快捷键 */
export const listenerShortcutKey = () => {
  document.addEventListener('keydown', handleShortcutKey, false)
  onUnmounted(() => {
    document.removeEventListener('keydown', handleShortcutKey, false)
  })
}

/** 选择默认视图 后续操作 */
const handleSelectDefaultViewAfter = () => {
  const key = editorState.menu.selectedKey
  const defaultPage = editorState.menu.menus.find((item) => item.key === 'default')
  if (!defaultPage) {
    editorState.menu.defaultPages = []
    return
  }
  const page = defaultPage?.children?.find((item) => item.key === key)
  if (!page) {
    editorState.menu.defaultPages = []
    return
  }
  editorState.menu.defaultPages = page?.types ?? []
}

/** 组件选中 */
export const componentPanelChecked = (record: ConfigComponent) => {
  if (record.disabled) return
  editorState.componentPanel.checked = record.key
  editorState.schemas.component = record.schemas as any
  editorState.schemas.global = record.global as any
}

/** 菜单选中事件 */
export const handleMenuSelect = ({ key }: { key: string }) => {
  message.destroy()
  if (key.indexOf('default_') !== -1) {
    editorState.isNotDefaultView = false
    editorState.menu.selectedKey = key
    editorState.menu.selectedKeys = [key]
    handleSelectDefaultViewAfter()
    return false
  }
  editorState.isNotDefaultView = true
  editorState.menu.selectedKey = key
  editorState.menu.selectedKeys = [key]
  const cfg = componentsConfig[key] as ComponentsConfig
  // editorState.componentPanel.checked = cfg.default
  componentPanelChecked(cfg.components[cfg.default])
  return true
}

/** 进入单视图模式 */
export const enterSingleGraphMode = (key: string, parentKey: string | undefined) => {
  debugRun(
    () => {
      message.destroy()
      message.info('进入单视图模式')
    },
    { debug: editorState.debug }
  )
  const idx = editorState.menu.openKeys.findIndex((item) => item === parentKey)
  if (idx < 0 && parentKey) {
    editorState.menu.openKeys.push(parentKey)
  }
  handleMenuSelect({ key })
  editorState.multiGraph = false
}

/** 进入多视图模式 */
export const enterMultiGraphMode = () => {
  debugRun(
    () => {
      message.destroy()
      message.info('进入单视图模式')
    },
    { debug: editorState.debug }
  )
  editorState.multiGraph = true
}

/** 返回事件 */
export const backEvent = () => {
  if (editorState.multiGraph) {
    window.open(window.origin, '_blank')
    return
  }
  Modal.confirm({
    title: '操作提示',
    content: '是否确实退出编辑模式?',
    onOk() {
      enterMultiGraphMode()
    }
  })
}
/** 默认选中 */
const handleDefaultSelected = () => {
  if (!editorState.menu.selectedKey) return
  if (handleMenuSelect({ key: editorState.menu.selectedKey })) {
    const key = editorState.menu.selectedKey
    const cfg = componentsConfig[key] as ComponentsConfig

    // 设置默认 Component Schemas
    const record = cfg.components[currentCheckedComponent.value as string]
    editorState.schemas.component = record.schemas as any
    editorState.schemas.global = record.global as any
  }
}

/** 初始化 指引 */
export const initialGuide = () => {
  // 指南是否已经查看完成
  if (editorState.doneGuide) {
    return
  }
  const guideConfig = config.projectSettings.guide
  const driver = ref<Driver>()
  driver.value = new Driver(
    guideConfig.options(() => {
      if (!driver.value?.hasNextStep()) {
        editorState.doneGuide = true
      }
    })
  )
  driver.value.defineSteps(guideConfig.steps)
  driver.value.start()
}
/** 初始化 拖拽 */
export const initialDrop = () => {
  // const tbody = document.querySelector('.el-table__body-wrapper tbody')
  // Sortable.create(tbody, {
  //   onEnd: ({ newIndex, oldIndex }) => {}
  // })
}
;(() => {
  handleDefaultSelected()
})()
